package com.soen6441.generics.example;

import com.soen6441.generics.Sort;
import com.soen6441.generics.Sortable;

import java.util.*;

/**
 * Created by User on 23/07/2015.
 */

public class TestDataStructure
{
    public static void main(String[] args)
    {
        /*GenericDataStructure<Integer> integerGenericDataStructure = new GenericDataStructure<>();
        integerGenericDataStructure.add(7);
        integerGenericDataStructure.add(2);
        integerGenericDataStructure.add(1);
        integerGenericDataStructure.atWork();

        GenericDataStructure<String> stringGenericDataStructure = new GenericDataStructure<>();
        stringGenericDataStructure.add("String");
        stringGenericDataStructure.add("Integer");
        stringGenericDataStructure.add("Person");
        stringGenericDataStructure.atWork();
*/
        GenericDataStructure<Person> personGenericDataStructure = new GenericDataStructure<>();
        personGenericDataStructure.add(new Person("zzz"));
        personGenericDataStructure.add(new Person("sss"));
        personGenericDataStructure.add(new Person("vvv"));
        personGenericDataStructure.atWork();
    }
}

class GenericDataStructure<R extends Comparable<R>>
{
    List<R> container = new ArrayList<>();

    public void add(R a)
    {
        container.add(a);
    }

    public void sort()
    {
        // preferred method.
        Sort<R> sorter = new Sort<>();
        R[] arr = (R[]) java.lang.reflect.Array.newInstance(container.get(0)
               .getClass(), container.size());
        container.toArray(arr);
        R[] newArr = sorter.sort(arr);
        container = Arrays.asList(newArr);
        //Collections.sort(container);

           // Another method.
        /*R[] arr = (R[]) java.lang.reflect.Array.newInstance(container.get(0)
                .getClass(), container.size());
        for (int i = 0; i < container.size(); i++) {
            arr[i] = container.get(i);
        }*/
    }

    public void atWork()
    {
        sort();
        for(R r : container)
        {
            System.out.println(r);
        }
    }
}

class Person implements Comparable<Person> {
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person(String name) {
        this.name = name;
    }

    @Override
    public int hashCode(){
        return super.hashCode();
    }

    @Override
    public String toString() {
        return "Person{" +
                "name= '" + name + '\'' +
                "hashCode= '" + hashCode() + '\'' +
                '}';
    }

    @Override
    public int compareTo(Person p) {
        return name.compareTo(p.name);
    }
}

